<template>
  <div class="bg-container" style="position: relative;width: 100%;height: 100%;">
    <!-- 旧图片 -->
    <div class="bg old-bg" v-if="oldBgUrl" :style="{
      'background-image': `url(${oldBgUrl})`,
    }"></div>

    <!-- 新图片 -->
    <div class="bg" style="position: relative;width: 100%;height: 100%;" :style="{
      'background-image': bgLoaded ? `url(${bgUrl})` : 'none',
      'opacity': bgLoaded ? 1 : 0,
      'transition': 'opacity 0.4s linear',
    }">
      <transition name="fade-q">
        <rain v-if="rainLeve > 0 && setting.weatherBg !== 'close'" :level="rainLeve"></rain>
      </transition>
      <transition name="fade">
        <div class="bg" v-if="!(rainLeve > 0 && setting.weatherBg !== 'close')"
          style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;" :style="{
            'background-image': bgLoaded ? `url(${bgUrl})` : 'none',
          }">
        </div>
      </transition>
    </div>
  </div>
</template>
<script>
export default {
  name: "ava-background",
}
</script>
<script setup>
import { onMounted, ref, defineProps, watch, onUnmounted } from 'vue'
import rain from "@/home/weather/rain.vue";
import { bus } from "@/lib/bus"; // 引入消息总线
import { storage } from "@/lib/storage";

const props = defineProps({
  src: {
    type: String,
    default: ''
  },
  weather: {
    type: Object,
    default: () => ({
      "cap": "",
      "icon": 0,
      "temp": 0.0,
      "tempDesc": 0,
    })
  }
})
const rainLeve = ref(0);
const bgLoaded = ref(false);
const isTransitioning = ref(false);
const bgUrl = ref('');
const oldBgUrl = ref('');
const imageCache = new Map(); // 图片缓存，避免重复加载

watch(() => props.weather, () => {
  if (!setting.value.weatherBg || setting.value.weatherBg === 'auto') {
    initLevel(props.weather.cap);
  }
})
watch(() => props.src, (newVal, oldVal) => {
  oldBgUrl.value = oldVal;
  console.log('oldVal', oldVal);
  if (newVal !== oldVal) {
    bgLoaded.value = false;
    loadBg();
  }
})

const initLevel = (cap) => {
  if (!cap) {
    return;
  }
  rainLeve.value = 0;
  setTimeout(() => {
    if (cap.indexOf('雨') >= 0) {
      if ((cap.indexOf('雷') >= 0 || cap.indexOf('大') >= 0)) {
        rainLeve.value = 3;
      } else if (cap.indexOf('中') >= 0) {
        rainLeve.value = 2;
      } else {
        rainLeve.value = 1;
      }
    } else {
      rainLeve.value = 0;
    }
  }, 1000);
}

const setting = ref({ cap: 'light', weatherBg: true });
const loadBg = () => {
  const url = props.src || 'https://www.yangshangzhen.com/bing/wallpaper';

  // 如果URL相同，不需要重新加载
  if (url === bgUrl.value) {
    return;
  }

  // 如果图片已经在缓存中，直接使用
  if (imageCache.has(url)) {
    oldBgUrl.value = bgUrl.value;
    bgUrl.value = url;
    isTransitioning.value = true;
    setTimeout(() => {
      bgLoaded.value = true;
    }, 500);
    isTransitioning.value = false;
    return;
  }

  // 预加载新图片
  const img = new window.Image();
  img.src = url;

  // 处理加载完成的情况
  img.onload = () => {
    // 将图片添加到缓存
    imageCache.set(url, img);
    // 保存旧图片URL用于过渡
    oldBgUrl.value = bgUrl.value;
    isTransitioning.value = true;

    // 设置新图片URL
    bgUrl.value = url;

    // 等待一小段时间确保DOM更新，然后显示新图片
    setTimeout(() => {
      bgLoaded.value = true;
      isTransitioning.value = false;

      // 短暂保留旧图片，确保过渡平滑
      setTimeout(() => {
        if (bgUrl.value === url) { // 确保在延迟期间没有新的图片请求
          oldBgUrl.value = '';
        }
      }, 500);
    }, 500);
  };

  // 处理加载失败的情况
  img.onerror = () => {
    console.error('图片加载失败:', url);
    bgLoaded.value = true; // 确保至少显示旧图片
  };
}

const initSetting = () => {
  storage.get('setting').then((res) => {
    if (res) {
      setting.value = JSON.parse(res);
      if (!setting.value.weatherBg || setting.value.weatherBg === 'auto') {
        initLevel(props.weather.cap);
      } else {
        initLevel(setting.value.weatherBg);
      }
    }
  });
}


onMounted(() => {
  loadBg();
  initSetting();

  // 监听 theme-changed 事件
  bus.on('setting-changed', () => {
    initSetting();
  });
})

onUnmounted(() => {
  // 移除事件监听
  bus.off('setting-changed');
  // 清理缓存
  imageCache.clear();
});
</script>


<style scoped lang="less">
.bg-container {
  position: fixed;
  right: 0;
}

.bg {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}

.old-bg {
  z-index: -1;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 1s linear;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-to,
.fade-leave-from {
  opacity: 1;
}

.fade-q-leave-active {
  transition: opacity 1s linear;
}


.fade-q-leave-to {
  opacity: 0;
}

.fade-q-leave-from {
  opacity: 1;
}
</style>